var ajaxResponseObj;
var CAT = 0;
var DIAGRAMS = 0; //select Diagram option
var CategoriesCache = {}; //object
var TotalsCache = {};
var StatsCache = {};
var shortMonthNames = ['Jan', 'Feb', 'Mar', 'Apr', 'Mai', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
var COLORS = ['#4572A7', '#C33E31', '#86A24C', '#3D2614'];
var PlotLabels=[];
var Cache = {}; //checked input in "select_categories""

/**
 * Am object that contain info about checkboxes that must be hidden.
 */
var CustomGraphsHidden = {};
var REQUEST_DATA = {  
  datefrom: 0,
  dateto: 0,
  categoryId: 0,
  timeunit: 0
}

function GetStats(categoryId)
{
  REQUEST_DATA.datefrom = document.getElementById('datefrom').value;
  REQUEST_DATA.dateto = document.getElementById('dateto').value;
  REQUEST_DATA.timeunit = document.getElementById('timeunit').value;
  REQUEST_DATA.action = "get-data";

  $.ajax({
    type: "GET",
    url: "../../../admin/api/GetCategoriesData.php",
    data:  REQUEST_DATA,
    success: GetStatsSuccess
  });
}

function GetStatsSuccess(response)
{
  ajaxResponseObj = eval('(' + response + ')');
  StatsCache[REQUEST_DATA.datefrom + ', ' + REQUEST_DATA.dateto + ', '  + REQUEST_DATA.timeunit] = ajaxResponseObj;
  PopulateTableResults(ajaxResponseObj);
  var data = GetMostPopularCategories(ajaxResponseObj);
  PlotAccordingToChoices(data, GetFlotTicks(ajaxResponseObj));
  DrawFlot(data, GetFlotTicks(ajaxResponseObj));
    
  REQUEST_DATA.action = "get-growth";

  $.ajax({
    type: "GET",
    url: "../../../admin/api/GetCategoriesData.php",
    data: REQUEST_DATA,
    success: getGrowthStatus
  });
}

function getGrowthStatus(obj)
{
   if (typeof CategoriesCache[REQUEST_DATA.dateto +','+ ' get-categories'] == 'undefined')
   {
    ajaxResponseObj = eval('(' + obj + ')');
    CategoriesCache[REQUEST_DATA.dateto +','+ ' get-categories'] = ajaxResponseObj;
    GetGrowth(ajaxResponseObj);  
   }
   
   else GetGrowth(CategoriesCache[REQUEST_DATA.dateto +','+ ' get-categories']);
}


function GetGrowth(obj)
{
  var i=0;
  var html = "<table id = 'growth'><tr>"
  + '<th class="green">Category_name</th>'
  + '<th class="green">First 2 weeks</th>'
  + '<th class="green">Last 2 weeks</th>'
  + '<th class="green">Coefficient</th>'
  + '</tr>';
 
  for (var key in obj)
    {
      if(i<10)
      {
        html += '<tr>'
        +'<td>'+ obj[key]['name'] +'</td>'
        +'<td>'+ obj[key]['views'] +'</td>'
        +'<td>'+ obj[key]['sec_views'] +'</td>'
        +'<td>'+ obj[key]['raport'] +'</td>'
        +'</tr>';
        i++;
      }
    }
  html+= '</table>';
  $('#fastest-growing-catrgories').html(html);
}



function CheckResponseStatus()
{
  var datefrom = document.getElementById('datefrom').value;
  var dateto = document.getElementById('dateto').value;
  REQUEST_DATA.timeunit = document.getElementById('timeunit').value;

  
 
  if (typeof StatsCache[datefrom + ', ' + dateto + ', ' + REQUEST_DATA.timeunit] != 'undefined')
  {
    if(StatsCache[datefrom + ', ' + dateto + ', ' + REQUEST_DATA.timeunit] != null)
    {
      var data = GetMostPopularCategories(StatsCache[datefrom + ', ' + dateto + ', ' + REQUEST_DATA.timeunit]);

      DrawFlot(data, GetFlotTicks(StatsCache[datefrom + ', ' + dateto + ', ' + REQUEST_DATA.timeunit]));
      PopulateTableResults(StatsCache[datefrom + ', ' + dateto + ', ' + REQUEST_DATA.timeunit]);
      GetGrowth(CategoriesCache[dateto +','+ ' get-categories']);
      
    } 
    else GetStats(0);   
  }

  else
  {
    GetStats(0);  
  }
}

function PlotAccordingToChoices(data, timeunit)
{
  var choiceContainer = $('#category_select_id');
  
  if(typeof Cache['getChecked'] == 'undefined' )
 $('#category_select_id').html(BuildCustomChoicesHTML(data));
 
  $(choiceContainer).find("select").bind("multiselectclick", 
                                      {data: data, timeunit: timeunit}, 
                                      OnClickCustomPlotChoise);
}

function BuildCustomChoicesHTML(data)
{
  var html = '<select id = "category_selector">';
  for (var key in data)
  {
    var categoryName = key;
    html += '<option';
    html += ' value="'+ categoryName +'">'+ categoryName +'</option>';
  }
  
    html += '</select>';
    html += '<script type="text/javascript">'
    +'$("select").multiselect({header: "Select an option", noneSelectedText: "Select an Category", selectedList: 1});'
    +'</script>';

  
  return html;
  
}

function OnClickCustomPlotChoise(event)
{
  var data = event.data.data;
  var timeunit = event.data.timeunit;
  var inputEl = event.currentTarget;
  
  Cache['getChecked'] = $("#category_selector").multiselect("getChecked");
  CustomGraphsHidden[inputEl.value] = !inputEl.checked;
  DrawFlot(data, timeunit);

}

function DrawFlot(data, object)
{

  var options = {
    
      legend: { 
                show: true,
                labelFormatter: function (label) {
                    var cb = label;
                    return cb;}
              },
              
      xaxis: {
      monthNames: shortMonthNames,
      mode: 'time',
      timeformat: '%d %b'
      
    },
    yaxis: {
      min: 0, max: 5000
    }
  };
 
  var series = [];
  var i = 0;

  $("#category_selector").multiselect("getChecked").each(function (val, input) {
    
    var key = $(input).val();

    if (key && data[key])
    {
          data.push(data[key]);
          series.push({
          label : key,
          color: COLORS[i++],
          data: data[key],
          tooltip: {
            show: true,
            tooltipFormatter: function(item) 
            {
              return _tooltipFormatter(item,item.series.color)
            }
          } 
          });
    }
  });

    options.xaxis.ticks= object; 

  
  window.priceHistoryGraph = new FlotWrapper("product-price-history-flot", series, options);

  function _tooltipFormatter(item, color)
  {
    var labelData = item.series.xaxis.ticks[item.dataIndex].label;
    var views = item.datapoint[1];
    return '<span class="content popup-shadow" style="border-color: ' + color + '"> <b> '+ item.series.label +'</b>&#44; on ' + labelData + '<b style = "color: ' + color + ';"> ' + views + '</b>  views </span>';
  }
}

function GetMostPopularCategories(obj)
{
  var data = [];
  var i=0;
  
 
  for (var key in obj) 
  {
    var nr_par=0;

      var pointer = [];

      for (var keys in obj[key])
      {
        if(nr_par % GetDaysNumber(REQUEST_DATA.datefrom, REQUEST_DATA.dateto,REQUEST_DATA.timeunit) == 0)
        {
          var point = [];
          point[0] = Date.parse(obj[key][keys]['range-start']);
          point[1] = obj[key][keys]['value'];
          pointer.push(point);       
        }
        
        nr_par++;
        data[key] = pointer;
      }
      i++;
  }
return data;
}